﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace viBook.Models
{
    public class AuthorRepository : IAuthorRepository
    {
        private readonly viBookContext context = new viBookContext();

        #region IAuthorRepository Members

        public IQueryable<Author> All
        {
            get { return context.Authors; }
        }

        public IQueryable<Author> AllIncluding(params Expression<Func<Author, object>>[] includeProperties)
        {
            IQueryable<Author> query = context.Authors;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Author Find(int id)
        {
            return context.Authors.Find(id);
        }

        public void InsertOrUpdate(Author author)
        {
            if (author.Id == default(int))
            {
                // New entity
                context.Authors.Add(author);
            }
            else
            {
                // Existing entity
                context.Entry(author).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            Author author = context.Authors.Find(id);
            context.Authors.Remove(author);
        }

        public void Save()
        {
            context.SaveChanges();
        }
        public IEnumerable<string> FindAuthors(string criteria, int limit)
        {
            return context.Authors.
                Where(c => c.AuthorName.ToLower().Contains(criteria.ToLower())).
                Take(limit).
                Select(c => c.AuthorName);
        }

        public int FindAuthorsiId(string authorName)
        {
            Author author = context.Authors.
                Where(c => c.AuthorName.ToLower().Equals(authorName.ToLower())).FirstOrDefault();
            if (author != null) return author.Id;
            else
            {
                var autho = new Author() {AuthorName = authorName};
                InsertOrUpdate(autho);
                Save();
                return autho.Id;
            }
        }

        #endregion

       
    }
    #region Nested type: IAuthorRepository

    public interface IAuthorRepository
    {
        IQueryable<Author> All { get; }
        IQueryable<Author> AllIncluding(params Expression<Func<Author, object>>[] includeProperties);
        Author Find(int id);
        void InsertOrUpdate(Author author);
        void Delete(int id);
        void Save();
        IEnumerable<string> FindAuthors(string criteria, int limit);
        int FindAuthorsiId(string authorName);
    }

    #endregion
}